package com.nowcoder.community.service;

import com.nowcoder.community.CommunityConstants.ActivationResult;
import com.nowcoder.community.contant.Role;
import com.nowcoder.community.entity.LoginTicket;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.repository.LoginTicketMapper;
import com.nowcoder.community.repository.UserMapper;
import com.nowcoder.community.utils.CommunityUtils;
import com.nowcoder.community.utils.MailClient;
import com.nowcoder.community.utils.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import sun.security.krb5.internal.Ticket;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private RedisTemplate redisTemplate;

/*    @Autowired
    private LoginTicketMapper loginTicketMapper;*/

    @Value("${community.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    /*
    * 注册用户
    * */
    public Map<String, Object> registerUser(User user){
        if (user == null)
            throw new IllegalArgumentException("user 对象不能为 null");

        Map<String, Object> map = new HashMap<>();
        // 进行空值判断
        if (StringUtils.isBlank(user.getUsername())){
            map.put("usernameMsg", "用户名不能为空");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())){
            map.put("passwordMsg", "密码不能为空");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())){
            map.put("emailMsg", "邮箱不能为空");
            return map;
        }

        // 判断 user 是否被注册
        User u = userMapper.findByUsername(user.getUsername());
        if (u != null){
            map.put("usernameMsg", "用户名已被注册");
            return map;
        }
        u = userMapper.findByEmail(user.getEmail());
        if (u != null){
            map.put("emailMsg", "邮箱已被注册");
            return map;
        }

        // 进行注册
        user.setStatus(0);
        user.setType(0);
        user.setSalt(CommunityUtils.generateUUID().substring(0, 5));
        user.setPassword(CommunityUtils.md5(user.getPassword(), user.getSalt()));
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        user.setActivationCode(CommunityUtils.generateUUID());
        user.setCreateTime(new Date());
        userMapper.insertUser(user);

        // 发送激活邮件
        // http://localhost:8000/community/activation/userId/activationCode
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        Context context = new Context();
        context.setVariable("email", user.getEmail());
        context.setVariable("url", url);
        String content = templateEngine.process("/mail/activation", context);
        mailClient.send(user.getEmail(), "账号激活", content);
        return map;
    }

    /*
    * 激活账号
    * */
    public ActivationResult activateUser(int userId, String activationCode){
        User user = userMapper.findById(userId);
        if (user == null){
            return ActivationResult.NO_SUCH_USER;
        }else if (user.getStatus() == 1){
            return ActivationResult.REPATED;
        }else if (user.getActivationCode().equals(activationCode)){
            userMapper.updateStatus(userId, 1);
            cleanUserCache(userId);
            return ActivationResult.SUCCESS;
        }else{
            return ActivationResult.INVALID_CODE;
        }
    }

    /*
    * 登录用户
    * */
    public Map<String, Object> loginUser(String username, String password, int expiredSeconds){
        Map<String, Object> map = new HashMap<>();

        // 空值判断
        if (StringUtils.isBlank(username)){
            map.put("usernameMsg", "用户名不能为空");
            return map;
        }
        if(StringUtils.isBlank(password)){
            map.put("passwordMsg", "密码不能为空");
            return map;
        }

        // 账号验证
        User user = userMapper.findByUsername(username);
        if (user == null){
            map.put("usernameMsg", "用户不存在");
            return map;
        }
        if (user.getStatus() == 0){
            map.put("usernameMsg", "用户未激活");
            return map;
        }
        if (!CommunityUtils.md5(password, user.getSalt()).equals(user.getPassword())){
            map.put("passwordMsg", "密码不正确");
            return map;
        }

        // 生成用户凭证
        LoginTicket ticket = new LoginTicket();
        ticket.setUserId(user.getId());
        ticket.setTicket(CommunityUtils.generateUUID());
        ticket.setStatus(0);
        ticket.setExpired(new Date(System.currentTimeMillis() + 1000 * expiredSeconds));
        // 将用户凭证存储到 redis
        String loginTicketRedisKey = RedisKeyUtil.getLoginTicketRedisKey(ticket.getTicket());
        redisTemplate.opsForValue().set(loginTicketRedisKey, ticket);
        map.put("ticket", ticket.getTicket());
        return map;
    }

    /*
    * 退出登录
    * */
    public void logoutUser(String ticket){
        String loginTicketRedisKey = RedisKeyUtil.getLoginTicketRedisKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(loginTicketRedisKey);
        loginTicket.setStatus(1);
        redisTemplate.opsForValue().set(loginTicketRedisKey, loginTicket);
    }


    public User findUserById(int id){
        User user = getUserCache(id);
        if (user == null){
            user = userMapper.findById(id);
            setUserCache(user);
        }
        return user;
    }

    public User findUserByUsername(String username){
        return userMapper.findByUsername(username);
    }

    // 修改密码
    /*
    * 判断邮箱是否存在
    * */
    public boolean isEmailExists(String email){
        if (email == null) return false;

        return userMapper.findByEmail(email) != null;
    }

    /*
    * 修改密码
    * */
    public void updatePassword(String email, String password){
        User user = userMapper.findByEmail(email);
        if (user == null)
            throw new IllegalArgumentException("邮箱不存在: " + email);

        user.setPassword(CommunityUtils.md5(password, user.getSalt()));
        userMapper.updatePassword(user.getId(), user.getPassword());
        cleanUserCache(user.getId());
    }

    public int updateHeader(int userId, String headerUrl){
        int rows = userMapper.updateHeaderUrl(userId, headerUrl);
        cleanUserCache(userId);
        return rows;
    }

    public LoginTicket findByTicket(String ticket){

        return (LoginTicket) redisTemplate.opsForValue().get(RedisKeyUtil.getLoginTicketRedisKey(ticket));
    }

    private User getUserCache(int userId){
        return (User) redisTemplate.opsForValue().get(RedisKeyUtil.getUserCacheRedisKey(userId));
    }

    private void setUserCache(User user){
        String userCacheRedisKey = RedisKeyUtil.getUserCacheRedisKey(user.getId());
        redisTemplate.opsForValue().set(userCacheRedisKey, user, 1, TimeUnit.HOURS);
    }

    private void cleanUserCache(int userId){
        redisTemplate.delete(RedisKeyUtil.getUserCacheRedisKey(userId));
    }
}
